/*
 * 设备管理页面视图
 * @Author: LuoQianJun
 * @Date: 2018-03-31 14:52:07
 * @Last Modified by: ljb
 * @Last Modified time: 2018-09-04 10:56:28
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>

    .v-admin-equipment-views {
        padding: 20px;
    }

</style>
<template>

	<div class="v-admin-equipment-views">

		<Tabs
			type="card"
			@on-click="changeTab">

			<TabPane
				:label="$t('equipment.equipment')"
				name="入库">
				<equipment-create
					ref="create"
					:loading="table_loading"
					:skin-detectors="skin_detectors"
					:devices="devices"
					:device-specs="device_specs"
					@postStore="postStoreData"
					@postStoreBuy="postStoreBuyData"/>
			</TabPane>

			<TabPane
				:label="$t('equipment.purchase_devices')"
				name="库存设备">

				<purchaseSearchForm
					ref="purchaseSearch"
					@search="confirmSearch"/>

				<purchase-index
					:loading="table_loading"
					:purchase-devices="purchase_devices.data"
					@showSellAdd="showSellComponent"
					@sort="confirmSearch"/>

				<br>
				<!-- 分页组件 -->

				<Row
					type="flex"
					justify="center">
					<Page
						:total="purchase_devices.total"
						:current="purchase_devices.current_page"
						:page-size="query_info.per_page"
						placement="top"
						show-sizer
						show-total
						@on-change="pageChange"
						@on-page-size-change="perPageChange"/>
				</Row>
			</TabPane>

			<TabPane
				:label="$t('equipment.sell_devices')"
				name="已售设备">

				<sellSearchForm
					ref="sellSearch"
					:customers="customers"
					@search="confirmSearch"/>

				<sell-index
					:loading="table_loading"
					:sell-devices="sell_devices.data"
					:customers="customers"
					@show="showAccoundIndex"
					@sort="confirmSearch"/>

				<br>
				<!-- 分页组件 -->

				<Row
					type="flex"
					justify="center">
					<Page
						:total="sell_devices.total"
						:current="sell_devices.current_page"
						:page-size="query_info.per_page"
						placement="top"
						show-sizer
						show-total
						@on-change="pageChange"
						@on-page-size-change="perPageChange"/>
				</Row>


			</TabPane>

			<TabPane
				:label="$t('equipment.machine_devices')"
				name="机器设备">
				<machineSearchForm
					ref="machineSearch"
					@search="confirmSearch"/>

				<machine-index
					:loading="table_loading"
					:machine-devices="machine_devices.data"
					:skin-detectors="skin_detectors"
					@show="showSpecDevice"/>
				<br>
				<!-- 分页组件 -->

				<Row
					type="flex"
					justify="center">
					<Page
						:total="machine_devices.total"
						:current="machine_devices.current_page"
						:page-size="query_info.per_page"
						placement="top"
						show-sizer
						show-total
						@on-change="pageChange"
						@on-page-size-change="perPageChange"/>
				</Row>


			</TabPane>

		</Tabs>

		<Modal
			v-model="show_modal"
			:title="$t('equipment.sold_devices')"
			class-name="vertical-middle-modal">

			<!-- 出售设备编辑组件 -->
			<sell-create
				ref="sell_create"
				:customers="customers"
				:skin-detectors="skin_detectors"
				:purchase-device ="device_detail"
				:show-modal="show_modal"
				@post="addSellDevice"/>

			<div slot="footer"/>

		</Modal>

		<Modal
			v-model="show_editModal"
			:title="$t('equipment.edit_machine_devices')"
			class-name="vertical-middle-modal">

			<!-- 机器设备编辑组件 -->
			<machine-edit
				ref="sell_edit"
				:device-specs="device_specs"
				:machine-detail ="machine_detail"
				:show-modal="show_editModal"
				@post="editSpecDevice"/>

			<div slot="footer"/>

		</Modal>

		<Modal
			v-model="show_deviceModal"
			:title="$t('equipment.account_information')"
			class-name="vertical-middle-modal"
			align="center"
			width="80%"
			@on-cancel="hide_deviceModal">
			<!-- 账号信息 -->
			<account-index
				ref="account_show"
				:loading="table_loading"
				:account-lists="account_lists"
				@show="showAccoundEdit"/>

			<div slot="footer"/>
		</Modal>

		<Modal
			v-model="show_editDeviceModal"
			:title="$t('equipment.modify_account_info')"
			class-name="vertical-middle-modal"
			@on-cancel="hide_editDeviceModal">
			<!-- 修改账信息 -->
			<account-edit
				ref="account_edit"
				:skin-detectors="skin_detectors"
				:account-details="account_details"
				:show-modal="show_editDeviceModal"
				@post="editAccoundDevice"/>
			<div slot="footer"/>
		</Modal>

	</div>

</template>

<script>

import API_LIST from 'src/API_LIST';
import { mapMutations } from 'vuex';
import qs from 'qs';
import { deleteEmptyValue } from 'src/utils/utils';
import purchaseIndex from './purchase/purchase-index';
import equipmentCreate from './create';
import purchaseSearchForm from './purchase/search-form';
import sellIndex from './sell/sell-index';
import sellCreate from './sell/create';
import sellSearchForm from './sell/search-form';
import machineIndex from './machine/machine-index';
import machineEdit from './machine/edit';
import machineSearchForm from './machine/search-form';
import accountIndex from './account/account-index';
import accountEdit from './account/edit';

export default {

	name: 'EquipmentViews',

	components: {
		purchaseIndex,
		equipmentCreate,
		sellIndex,
		sellCreate,
		machineIndex,
		machineEdit,
		purchaseSearchForm,
		sellSearchForm,
		machineSearchForm,
		accountIndex,
		accountEdit,
	},
	data() {
		return {
			table_loading: false, // 表格更新时的loading

			show_modal: false, // 弹框的控制

			show_editModal: false, // 机器设备编辑弹窗的控制

			show_deviceModal: false, // 账号列表信息弹窗的控制

			show_editDeviceModal: false, // 修改账户信息弹窗的控制

			equipment_types: {}, // 设备种类

			skin_detectors: {}, // 肤质检测仪类型

			devices: [], // 已有设备型号

			device_specs: [], // 试妆参数编号

			customers: {}, // pad类型,

			purchase_devices: {}, // 入库设备相关信息

			sell_devices: {}, // 卖出设备相关信息

			machine_devices: {}, // 机器设备相关信息

			device_detail: {}, // 已售设备详情

			machine_detail: {}, // 机器设备详情

			account_lists: [], // 账号列表信息详情

			account_details: {}, // 账户信息详情

			account_id: '', // 已售设备id

			query_info: {

				page: 1,

				per_page: 20,

				uuid: '',

				device_name: '',

				specification: '',

				producer: '',

				buyer: '',

				time_range: [],

				operator: '',

				customer_id: '',

				order_bys: [],

			},

			search_info: {

				page: 1,

			},

			per_page: {
				purchase: 10,
				sell: 10,
				machine: 10,
			}, // 每页条数


			is_purchase: '', // 判断当前在入库设备列表 还是 卖出设备列表
		};
	},
	mounted() {
		this.fetchEquipmentCategory();
	},
	methods: {

		...mapMutations('spinShow', [
			'showSpin',
			'closeSpin',
		]),

		/**
		 * 重置搜索参数
		 * @return {undefined}
		 */
		resetSearchParam() {
			this.query_info = {
				page: 1,

				per_page: 20,

				uuid: '',

				device_name: '',

				specification: '',

				producer: '',

				buyer: '',

				time_range: [],

				operator: '',

				customer_id: '',

				order_bys: [],
			};

			this.search_info = {

				page: 1,

			};

			this.$refs.purchaseSearch.resetParam();
			this.$refs.sellSearch.resetParam();
			this.$refs.machineSearch.resetParam();
		},

		/**
         * 显示卖出设备弹出框
         * @param  {Object} record {设备对象}
         * @return {undefined}
         */
		showSellComponent(record) {
			this.device_detail = record;
			this.show_modal = true;
		},

		/**
         * 显示机器设备弹出框
         * @param  {Object} record {设备对象}
         * @return {undefined}
         */
		showSpecDevice(record) {
			this.machine_detail = record;
			this.show_editModal = true;
		},

		/**
		 * 显示账号信息列表弹出窗
		 * @param  {Array} record {账号信息数组}
		 * @param {String} id {账号id}
		 * @return {undefined}
		 */
		showAccoundIndex(record, id) {
			this.account_lists = record;
			this.account_id = id;
			this.show_deviceModal = true;
		},

		/**
		 * 账号信息列表关闭弹出窗回调函数
		 * @return {undefined}
		 */
		hide_deviceModal() {
			this.account_lists = [];
			this.account_id = '';
		},

		/**
		 * 显示修改账号信息列表弹出窗
		 * @param {Array} record {肤质检测仪数据}
		 * @return {undefined}
		 */
		showAccoundEdit(record) {
			this.account_details = record;
			this.show_editDeviceModal = true;
		},

		/**
		 * 修改账号信息列表关闭弹出窗回调函数
		 * @return {undefined}
		 */
		hide_editDeviceModal() {
			this.account_details = {};
		},

		/**
         * 页码改变
         * @param  {string} pageNumber {当前页码}
         * @return {undefined}
         */
		pageChange(pageNumber) {
			this.search_info.page = pageNumber;
			this.search_info.per_page = this.query_info.per_page;

			this.getDeviceList(this.is_purchase);
		},

		/**
         * 每页显示数改变
         * @param  {string} per_page {当前每页显示数}
         * @return {undefined}
         */
		perPageChange(per_page) {
			this.search_info.per_page = per_page;

			this.query_info.per_page = per_page;

			switch (this.is_purchase) {
			case '库存设备':
				this.per_page.purchase = per_page;

				break;
			case '已售设备':
				this.per_page.sell = per_page;

				break;
			case '机器设备':
				this.per_page.machine = per_page;

				break;
			default:
				break;
			}

			this.getDeviceList(this.is_purchase);
		},

		/**
         * 确认搜索
         * @param  {Object} param {搜索的参数对象}
         * @return {undefined}
         */
		confirmSearch({
			code, device_code, uuid, device_name, specification, producer, buyer, time_range, operator, customer_id, order_by, sort,
		}) {
			this.query_info.device_code = device_code || '';
			this.query_info.code = code || '';
			this.query_info.uuid = uuid || '';
			this.query_info.device_name = device_name || '';
			this.query_info.specification = specification || '';
			this.query_info.producer = producer || '';
			this.query_info.buyer = buyer || '';
			this.query_info.time_range = time_range || [];
			this.query_info.operator = operator || '';
			this.query_info.customer_id = customer_id || '';
			this.query_info.order_bys = order_by && sort ? [{ order_by, sort }] : [];

			this.search_info = JSON.parse(JSON.stringify(this.query_info));

			this.getDeviceList(this.is_purchase);
		},

		/**
		 * 获取设备列表信息
		 * @param {String} name {列表名称}
		 * @return {undefined}
		 */
		getDeviceList(name) {
			switch (name) {
			case '库存设备':
				this.fetchPurchaseDeviceList(this.search_info);

				break;
			case '已售设备':
				this.fetchSellDeviceList(this.search_info);

				break;
			case '机器设备':
				this.fetchMachineDeviceList(this.search_info);

				break;
			default:
				break;
			}
		},

		/**
         * 提交出售设备
         * @param  {Object} param {post请求所需的参数对象}
         * @return {undefined}
         */
		addSellDevice(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(API_LIST.ADD_SELL_EQUIPMENT, param)

				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('equipment.sell_device_success'));

					this.$refs.sell_create.handleReset('formValidate');

					this.show_modal = false;

					this.fetchPurchaseDeviceList(this.search_info);
				})

				.catch((err) => {
					this.$Message.error(err.message);
				})

				.then(this.closeSpin);
		},

		/**
         * 更新机器设备
         * @param  {Object} param {post请求所需的参数对象}
		 * @param {String} id {机器设备id}
         * @return {undefined}
         */
		editSpecDevice(id, param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(`${API_LIST.EDIT_SPEC_EQUIPMENT}/${id}`, param)

				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.update_success'));

					this.$refs.sell_edit.handleReset('formValidate');

					this.show_editModal = false;

					this.fetchMachineDeviceList(this.search_info);
				})

				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})

				.then(this.closeSpin);
		},

		/**
         * 切换tab
         * @param  {string} tab_name {tab的name}
         * @return {undefined}
         */
		changeTab(tab_name) {
			this.resetSearchParam();

			switch (tab_name) {
			case '库存设备':
				this.sell_devices = {};
				this.is_purchase = tab_name;
				this.query_info.per_page = this.per_page.purchase;
				this.fetchPurchaseDeviceList(this.query_info);

				break;
			case '已售设备':
				this.purchase_devices = {};
				this.is_purchase = tab_name;
				this.query_info.per_page = this.per_page.sell;
				this.fetchSellDeviceList(this.query_info);

				break;
			case '机器设备':
				this.machine_devices = {};
				this.is_purchase = tab_name;
				this.query_info.per_page = this.per_page.machine;
				this.fetchMachineDeviceList(this.query_info);

				break;
			default:
				this.purchase_devices = {};
				this.sell_devices = {};
				this.is_purchase = tab_name;
				break;
			}
		},

		/**
         * 获取新增入库分类信息
         * @return {undefined}
         */
		fetchEquipmentCategory() {
			this.showSpin();

			this.$http.get(`${API_LIST.EQUIPMENT}/create`)

				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.skin_detectors = data.skin_detectors;

					this.devices = data.devices;

					this.customers = data.customers;

					this.device_specs = data.device_specs;
				})

				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})

				.then(this.closeSpin);
		},

		/**
         * 获取库存设备列表
         * @param  {Object} param {搜索列表的参数}
         * @return {undefined}
         */
		fetchPurchaseDeviceList(param) {
			this.table_loading = true;

			const query_str = qs.stringify(deleteEmptyValue(param));

			this.$http.get(`${API_LIST.EQUIPMENT}?${query_str}`)

				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.purchase_devices = data.purchase_devices;
				})

				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})

				.then(() => { this.table_loading = false; });
		},

		/**
         * 获取已售设备列表
         * @param  {Object} param {搜索列表的参数}
         * @return {undefined}
         */
		fetchSellDeviceList(param) {
			this.table_loading = true;

			const query_str = qs.stringify(deleteEmptyValue(param));

			this.$http.get(`${API_LIST.SELL_EQUIPMENT}?${query_str}`)

				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.sell_devices = data.sell_devices;
					// 更新账号信息列表
					if (this.account_id) {
						const [devices_list] = data.sell_devices.data.filter(item => item.id === this.account_id);
						this.account_lists = devices_list.device_accounts;
					}
				})

				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})

				.then(() => { this.table_loading = false; });
		},

		/**
         * 获取机械设备列表
         * @param  {Object} param {搜索列表的参数}
         * @return {undefined}
         */
		fetchMachineDeviceList(param) {
			this.table_loading = true;

			const query_str = qs.stringify(deleteEmptyValue(param));

			this.$http.get(`${API_LIST.MACHINE_EQUIPMENT}?${query_str}`)

				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.machine_devices = data.devices;
				})

				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})

				.then(() => { this.table_loading = false; });
		},

		/**
         * 新增入库
		 * @param  {Object} param {post请求所需的参数对象}
         * @return {undefined}
         */
		postStoreData(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(API_LIST.EQUIPMENT, param)

				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.create_success'));

					this.$refs.create.handleReset('formValidate');

					this.fetchEquipmentCategory();
				})

				.catch((err) => {
					this.$Message.error(err.message);
				})

				.then(this.closeSpin);
		},

		/**
         * 新增已有入库
		 * @param {Object} param {post请求所需的参数对象}
         * @return {undefined}
         */
		postStoreBuyData(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(API_LIST.ADD_BUY_EQUIPMENT, param)

				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.create_success'));

					this.$refs.create.handleReset('storeBuyValidate');
				})

				.catch((err) => {
					this.$Message.error(err.message);
				})

				.then(this.closeSpin);
		},

		/**
		 * 修改账户信息
		 * @param  {Object} param {post请求所需的参数对象}
         * @return {undefined}
		 */
		editAccoundDevice(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(`${API_LIST.ADMIN_UPDATA_ACCOUNT_INFO}`, param)

				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.update_success'));

					this.$refs.account_edit.handleReset('formValidate');

					this.show_editDeviceModal = false;

					this.fetchSellDeviceList(this.search_info);
				})

				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})

				.then(this.closeSpin);
		},
	},
};
</script>
